package com.nuanshui.framework.lang;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import com.nuanshui.framework.utils.model.StringObjPair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class MapUtil {
	/**
	 * 方法名称:transMapToString 传入参数:map 返回值:String 形如
	 * username'chenziwen^password'1234
	 */
	@SuppressWarnings("rawtypes")
	public static String params(final Map map) {
		Map.Entry entry;
		StringBuilder sb = new StringBuilder();
		int index = 0;
		for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
			if (index > 0) {
				sb.append("&");
			}
			entry = (Map.Entry) iterator.next();
			sb.append(entry.getKey().toString());
			sb.append("=");
			sb.append(entry.getValue().toString());
			index++;
		}
		return sb.toString();
	}
	
	public static String params(final ArrayList<StringObjPair> list) {

		StringBuilder sb = new StringBuilder();
		
		for(int i=0;i<list.size();i++) {
			if (i > 0) {
				sb.append("&");
			}
			StringObjPair item=list.get(i);
			sb.append(item.getKey().toString());
			sb.append("=");
			sb.append(item.getValue().toString());
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws IOException {
		testParams();
	}
	
	public static void testParams()
	{
		Map<String,String> paramsMap=new HashMap<String,String>();
		paramsMap.put("a", "1");
		paramsMap.put("b", "2");
		paramsMap.put("c", "3");
		
		String result=MapUtil.params(paramsMap);
		System.out.println(result);
	}
	
    /**
     * 粗略解析返回参数
     * @author Junyan2015
     * @date 2016年4月20日 下午3:43:27
     * @since
     */
    public static Map<String, Object> getMapFromXMLString(String xmlString) throws ParserConfigurationException, IOException, SAXException {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      ByteArrayInputStream is = null;
      if (xmlString != null && !"".equals(xmlString.trim())) {
          is = new ByteArrayInputStream(xmlString.getBytes());
      }
      Document document = builder.parse(is);
      //获取到document里面的全部结点
      NodeList allNodes = document.getFirstChild().getChildNodes();
      Node node;
      Map<String, Object> map = new LinkedHashMap<String, Object>();
      int i = 0;
      while (i < allNodes.getLength()) {
          node = allNodes.item(i);
          if (node instanceof Element) {
              map.put(node.getNodeName(), node.getNodeValue());
          }
          i++;
      }
      return map;

  }

}
